<?php

// If the user wants to log out... do it
if (isset($_GET["logout"])) {
    $_SESSION = null;
    header("Location: .");
}

session_name("ec2Tracks");
session_start();

require_once("Util.php");
require_once('GoogleClient/Google_Client.php');
require_once('GoogleClient/contrib/Google_Oauth2Service.php');
require_once("GoogleAuthenticator.php");


define ("FEET_PER_METER", 3.2808399);
define ("INI_FILE", "/mnt/vol1/www/configs/tracks.ini");

if (!file_exists(INI_FILE)) {
    echo "INI file (" . INI_FILE . ") does not exist!";
    exit;
}

$iniOptions = parse_ini_file(INI_FILE, true);
if ($iniOptions === false) {
    echo "Failed to parse INI file (" . INI_FILE . ")!";
    exit;
}

if (!isset($iniOptions["mysql"])) {
    echo "INI file (" . INI_FILE . ") missing section '[mysql]'.";
    exit;
}

foreach ($iniOptions["mysql"] as $option => $value) {
    switch ($option) {
        case "server":
            define("MYSQL_SERVER", $value);
            break;
        case "database":
            define("MYSQL_DBASE", $value);
            break;
        case "user":
            define("MYSQL_USER", $value);
            break;
        case "password":
            define("MYSQL_PASSWORD", $value);
            break;
        default:
            echo "Unknown key/value ($option/$value) pair specified in ini file (" . INI_FILE .").";
            exit;
    }
}

foreach ($iniOptions["google"] as $option => $value) {
    switch ($option) {
        case "apiID":
            define ("GOOGLE_API_ID", $value);
            break;
        case "clientID":
            define ("GOOGLE_CLIENT_ID", $value);
            break;
        case "clientSecret":
            define ("GOOGLE_CLIENT_SECRET", $value);
            break;
        case "redirectURI":
            define ("GOOGLE_REDIRECT_URI", $value);
            break;
        case "applicationName":
            define ("GOOGLE_APP_NAME", $value);
            break;
        default:
            echo "Unknown key/value ($option/$value) pair specified in ini file (" . INI_FILE .").";
            exit;
    }
}

foreach ($iniOptions["gdal"] as $option => $value) {
    switch ($option) {
        case "ogr2ogr":
            define ("OGR2OGR" , $value);
            break;
        default:
            echo "Unknown key/value ($option/$value) pair specified in ini file (" . INI_FILE .").";
            exit;
    }
}

foreach ($iniOptions["totp"] as $option => $value) {
    switch ($option) {
        case "key":
            define ("TOTP_SECRET", $value);
            break;
        default:
            echo "Unknown key/value ($option/$value) pair specified in ini file (" . INI_FILE .").";
            exit;
    }
}

foreach ($iniOptions["mytopo"] as $option => $value) {
    switch ($option) {
        case "partnerid":
            define ("MYTOPO_PARTNER_ID", $value);
            break;
        case "secretkey":
            define ("MYTOPO_SECRET_KEY", $value);
            break;
        default:
            echo "Unknown key/value ($option/$value) pair specified in ini file (" . INI_FILE .").";
            exit;
    }
}

if (!defined("MYSQL_SERVER")) {
    echo "mysql server is not defined in the ini file (" . INI_FILE . ").";
    exit;
}

if (!defined("MYSQL_DBASE")) {
    echo "mysql database is not defined in the ini file (" . INI_FILE . ").";
    exit;
}

if (!defined("MYSQL_USER")) {
    echo "mysql user is not defined in the ini file (" . INI_FILE . ").";
    exit;
}

if (!defined("MYSQL_PASSWORD")) {
    echo "mysql password is not defined in the ini file (" . INI_FILE . ").";
    exit;
}

if (!defined("OGR2OGR")) {
    echo "ogr2ogr path is not defined in the ini file (" . INI_FILE . ").";
    exit;
}

if (!defined("GOOGLE_API_ID")) {
    echo "Google API ID is not defined in the ini file (" . INI_FILE . ").";
    exit;
}

if (!defined("GOOGLE_CLIENT_ID")) {
    echo "Google Client ID is not defined in the ini file (" . INI_FILE . ").";
    exit;
}

if (!defined("GOOGLE_CLIENT_SECRET")) {
    echo "Google Client secret is not defined in the ini file (" . INI_FILE . ").";
    exit;
}

if (!defined("GOOGLE_REDIRECT_URI")) {
    echo "Google Client redirect URI is not defined in the ini file (" . INI_FILE . ").";
    exit;
}

if (!defined("GOOGLE_APP_NAME")) {
    echo "Google app name is not defined in the ini file (" . INI_FILE . ").";
    exit;
}

if (!defined("TOTP_SECRET")) {
    echo "TOTP key is not defined in the ini file (" . INI_FILE . ").";
    exit;
}

if (!defined("MYTOPO_PARTNER_ID")) {
    echo "MyTopo Partner ID is not defined in the ini file (" . INI_FILE . ").";
    exit;
}

if (!defined("MYTOPO_SECRET_KEY")) {
    echo "MyTopo Secret Key  is not defined in the ini file (" . INI_FILE . ").";
    exit;
}

$analytics = "<script type=\"text/javascript\" src=\"/analytics.js\"></script>";

try {
    $db = new PDO(
        "mysql:host=" . MYSQL_SERVER . ";dbname=" . MYSQL_DBASE, 
        MYSQL_USER, 
        MYSQL_PASSWORD,
        array (PDO::ATTR_PERSISTENT => true)
    );
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}

$client = new Google_Client();
$client->setApplicationName(GOOGLE_APP_NAME);
$client->setClientId(GOOGLE_CLIENT_ID);
$client->setClientSecret(GOOGLE_CLIENT_SECRET);
$client->setRedirectUri(GOOGLE_REDIRECT_URI);
$oauth2 = new Google_Oauth2Service($client);
$connect = "";
$loggedIn = false;

if (isset($_GET['code'])) {
    $client->authenticate();
    $_SESSION['token'] = $client->getAccessToken();
    $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
    header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}

if (isset($_SESSION['token'])) {
    $client->setAccessToken($_SESSION['token']);
}

if (isset($_REQUEST['logout'])) {
    unset($_SESSION['token']);
    unset($_SESSION['authed']);
    $client->revokeToken();
}

$_SESSION["authed"] = false;
$_SESSION["nickname"] = "guest";

if ($client->getAccessToken()) {
    $user = $oauth2->userinfo->get();
    $email = filter_var($user['email'], FILTER_SANITIZE_EMAIL);
    $img = (isset($user['picture']) ? filter_var($user['picture'], FILTER_VALIDATE_URL) : "");
    $personMarkup = "$email<div><img src='$img?sz=50'></div>";
    $stmt = $db->prepare("SELECT gmailAddr, nickname FROM users WHERE gmailAddr = :email");
    $stmt->execute(array("email" => $email));
    if ($stmt->rowCount() == 1) {
        $_SESSION["authed"] = true;
        $_SESSION["email"] = $email;
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if (trim($row["nickname"]) != "") {
            $_SESSION["nickname"] = $row["nickname"];
        } else {
            $_SESSION["nickname"] = $email;
        }
    } else {
        $logInOut = '<a href="?logout">logout</a>';
    }
    $_SESSION['token'] = $client->getAccessToken();
} else {
    $authUrl = $client->createAuthUrl();
    $logInOut = "<a href='$authUrl'>Login</a>";
}

if ($_SESSION["authed"]) {
    $logInOut = '<a href="?logout">logout</a>';
}
?>
